package com.jx.mlxg.utils;

import com.alibaba.fastjson.JSONObject;
import com.jx.mlxg.entity.Addresses;
import com.lop.open.api.sdk.DefaultDomainApiClient;
import com.lop.open.api.sdk.domain.ECAP.CommonCreateOrderApi.commonCreateOrderV1.*;
import com.lop.open.api.sdk.plugin.LopPlugin;
import com.lop.open.api.sdk.plugin.factory.OAuth2PluginFactory;
import com.lop.open.api.sdk.request.ECAP.EcapV1OrdersCreateLopRequest;
import com.lop.open.api.sdk.response.ECAP.EcapV1OrdersCreateLopResponse;
import lombok.extern.slf4j.Slf4j;
//import com.xinbiao.controller.param.AllocateFacilityAndOtherPartParam;
//import com.xinbiao.exception.XBException;
//import com.xinbiao.model.AddressInfo;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

@Slf4j
public class JDUtil {
    //沙箱环境的地址的创建订单地址
//    private static String CALL_URL_BOX="https://uat-api.jdl.com/ecap/v1/orders/create";
      private static String CALL_URL_BOX="https://uat-api.jdl.com/";

    //生产环境的地址
    private static String CALL_URL_PROD = "https://api.jdl.com/";

    //    appkey及appsecret生产环境和预发环境均通用
    //应用id
    private static String appKey = "57bcb2b770ee4f548f5954e1443805e9";
    //AppSecret
    private static String AppSecret= "32e0041fd3fb4d04b8ba1000b93e2a8f";

    private static String UatAccessToken= "4eb0d75f66564d84a9531d4d6a51d1ac";//2026-05-09 09:55:33 到期，到期后需重新授权
    private static String accessToken = "d8a2d135a44d420db9eba7dd081f9e3f";//2026-05-09 09:55:33 到期，到期后需重新授权

    //DefaultDomainApiClient对象全局只需要创建一次
    private static DefaultDomainApiClient client = new DefaultDomainApiClient(CALL_URL_PROD,500,15000);

    public static Map<String, Object> JDCreateOrder(Map param){
        try {
            //入参对象（请记得更换为自己要使用的接口入参对象）
            EcapV1OrdersCreateLopRequest request = new EcapV1OrdersCreateLopRequest();
            CommonCreateOrderRequest requestDTO = new CommonCreateOrderRequest();
            requestDTO.setOrderId(param.get("orderId").toString());
            requestDTO.setRemark(param.get("remark").toString());
//             创建指定的 LocalDateTime 对象，用于预定上门取件时间
//            LocalDateTime localDateTime = LocalDateTime.of(2024, 6, 1, 10, 0, 0);
//            // 转换为 Date 对象
//            Date specifiedDate = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
//            // 创建指定的 LocalDateTime 对象
//            LocalDateTime end = LocalDateTime.of(2024, 6, 1, 12, 0, 0);
//            // 转换为 Date 对象
//            Date endTime = Date.from(end.atZone(ZoneId.systemDefault()).toInstant());
//            requestDTO.setPickupStartTime(specifiedDate);
//            requestDTO.setPickupEndTime(endTime);
            long currentTimestamp = System.currentTimeMillis();
           log.info("当前的毫秒级时间戳:{}" , currentTimestamp);

            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.HOUR_OF_DAY, 2); // 当前时间加 2 小时
            long futureTimestamp = calendar.getTimeInMillis();
            log.info("当前时间加 2 小时后的毫秒级时间戳:{} " , futureTimestamp);

            //创建发货人和收货人
            Contact senderContact  = new Contact();

            senderContact.setFullAddress("天津市东丽区军粮城街道天津东丽区军粮城街道津塘公路军粮城轻轨车站南侧东丽区广福商业中心");
            senderContact.setName("小聚香酱料供应链");
            senderContact.setMobile("18822699607");

            Contact receiverContact = new Contact();//收件人地址
            receiverContact.setFullAddress(param.get("address").toString());//param.getAddress()
            receiverContact.setName(param.get("name").toString());
            receiverContact.setMobile(param.get("phoneNumber").toString());
            requestDTO.setReceiverContact(receiverContact);
            requestDTO.setSenderContact(senderContact);
            requestDTO.setPickupStartTime(currentTimestamp);
            requestDTO.setPickupEndTime(futureTimestamp);
            //产品信息:京东标快还是京东特快
            CommonProductInfo commonProductInfo = new CommonProductInfo();
            commonProductInfo.setProductCode("fr-m-0004");//京东标快
            requestDTO.setProductsReq(commonProductInfo);

            //下单来源:
            requestDTO.setOrderOrigin(4);//1:电商平台的商家（即京东物流的签约商家）发给C端用户的快递服务，或者企业发C端、B端，但重量（泡重比）小于30kg的业务
            //客户编码 ，orderOrigin为 1 或者 2 时必填；orderOrigin为0时不要传此参数；与京东物流签约后生成，长度1-32
            requestDTO.setCustomerCode("EBU4418054998613");
            requestDTO.setBusinessUnitCode("EBU4418054998613");
            requestDTO.setSettleType(3);//设置付款方式，3为月结
            requestDTO.setPickupType(1);
            requestDTO.setDeliveryType(1);
            //货品信息；寄递货物的基础信息，包括重量体积以及包裹的长宽高等
            CommonCargoInfo commonCargoInfo = new CommonCargoInfo();
            commonCargoInfo.setName(param.get("productName").toString());
            commonCargoInfo.setQuantity((Integer) param.get("quantity"));//件数
            commonCargoInfo.setWeight(new BigDecimal((Integer) param.get("quantity")*50));//重量
            commonCargoInfo.setWidth(BigDecimal.valueOf(10));
            commonCargoInfo.setHight(BigDecimal.valueOf(10));
            BigDecimal multiply = new BigDecimal(10)
                    .multiply(new BigDecimal(10)
                            .multiply(new BigDecimal(10))
                            .setScale(2, BigDecimal.ROUND_HALF_UP));
            commonCargoInfo.setVolume(multiply);//体积，单位：cm³；必填；保留小数点后两位；必须大于0，
            List<CommonCargoInfo> commonCargoInfos = Arrays.asList(commonCargoInfo);
            requestDTO.setCargoes(commonCargoInfos);
            C2BAddedSettleTypeInfo c2bAddedSettleTypeInfo = new C2BAddedSettleTypeInfo();
            c2bAddedSettleTypeInfo.setBasicFreigthSettleType(3);
            c2bAddedSettleTypeInfo.setPackageServiceSettleType(3);
            c2bAddedSettleTypeInfo.setGuaranteeMoneyServiceSettleType(3);
            requestDTO.setC2bAddedSettleTypeInfo(c2bAddedSettleTypeInfo);
            request.setRequest(requestDTO);
            log.info("请求参数{}",request);
            log.info("请求参数requestDto{}",requestDTO);

            LopPlugin lopPlugin = OAuth2PluginFactory.produceLopPlugin(appKey, AppSecret,accessToken);
            request.addLopPlugin(lopPlugin);

            EcapV1OrdersCreateLopResponse response = client.execute(request);
            System.out.println("京东下单接口返回信息：");
            System.out.println(response.getMsg());
            String msg = response.getMsg();
            Map resultMap = parseCodeFromResponse(msg);
            return resultMap;
        }catch (Exception e) {
            e.printStackTrace();
        }
        return new HashMap<>();
    }

    public static Map<String, Object> parseCodeFromResponse(String jsonResponse) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            JSONObject responseObj = JSONObject.parseObject(jsonResponse);
            JSONObject responseObject = responseObj.getJSONObject("response");
            JSONObject contentObject = responseObject.getJSONObject("content");

            // 获取 code 值
            Integer code = contentObject.getInteger("code");
            resultMap.put("code", code != null ? code.toString() : "500");

            try {
                // 尝试获取 waybillCode，如果不存在则返回空字符串
                String waybillCode = contentObject.getJSONObject("data").getString("waybillCode");
                resultMap.put("waybillCode", waybillCode != null ? waybillCode : "");
            } catch (Exception e) {
                // 如果 waybillCode 获取失败，记录日志但继续执行
                System.err.println("Failed to retrieve waybillCode: " + e.getMessage());
                resultMap.put("waybillCode", "");
            }

            // 获取 subMsg 值
            String subMsg = contentObject.getString("subMsg");
            resultMap.put("subMsg", subMsg != null ? subMsg : "");

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code", "500");
            resultMap.put("waybillCode", "");
            resultMap.put("subMsg", "系统错误");
        }
        return resultMap;
    }

}